/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-04-24
 * Time: 22:46
 */

class Node{
    public int value;
    public Node next;

    public Node(int Data){
        this.value = Data;
    }

//    public Node removeLastKthNode(Node head,int lastKth) {
//        if(head==null||lastKth<1) {
//            return head;
//        }
//        //定义fast节点
//        Node fast =head;
//        Node slow = head;
//        //先让fast走k步
//        while(fast!=null&&lastKth!=0) {
//            fast =fast.next;
//            lastKth--;
//        }
//        Node prev = null;
//        //之后fast和slow一起走，走到fast为空
//        while(fast!=null) {
//            fast = fast.next;
//            prev =slow;
//            slow = slow.next;
//        }
//        //删除倒数第k个节点
//            prev.next =slow.next;
//
//        return head;
//    }

    public Node removeLastKthNode(Node head,int lastKth) {
        if(head==null||lastKth<1) {
            return head;
        }
        Node cur = head;
        while(cur!=null) {
            lastKth--;
            cur = cur.next;
        }
        if(lastKth>0) {
            return head;
        }
        if(lastKth==0) {
            head= head.next;
        }
        if(lastKth<0) {
            cur =head;
            while(++lastKth!=0) {
                cur =cur.next;
            }
            cur.next = cur.next.next;
        }

        return head;
    }

    public void linkedListDisplay(Node head) {
        Node cur = head;
        while(cur!=null) {
            System.out.print(cur.value+" ");
            cur =cur.next;
        }
        System.out.println();
    }

}

public class TestDemo {

    public static void main(String[] args) {
        Node node = new Node(0);
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(5);
        Node node6 = new Node(6);
        node1.next =node2;
        node2.next =node3;
        node3.next =node4;
        node4.next=node5;
        node5.next = node6;
        node6.next=null;
        node.linkedListDisplay(node1);
        node.removeLastKthNode(node1,1);
        node.linkedListDisplay(node1);

    }

}
